package cn.cloudtogo.server.atomapi;

import cn.cloudtogo.common.atomapi.token.ApiToken;
import cn.cloudtogo.common.atomapi.token.ApiTokenQuery;
import cn.cloudtogo.common.types.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import static cn.cloudtogo.server.WebResponse.*;

/**
 * @author yaolianhua789@gmail.com
 **/
@RestController
@RequestMapping("/{uuid}/token")
@Slf4j
public class ApiTokenController {

    private final ApiTokenQuery apiTokenQuery;
    private final GendbApiTokenService gendbApiTokenService;

    public ApiTokenController(ApiTokenQuery apiTokenQuery,
                              GendbApiTokenService gendbApiTokenService) {
        this.apiTokenQuery = apiTokenQuery;
        this.gendbApiTokenService = gendbApiTokenService;
    }

    @GetMapping
    public ResponseEntity<Result<ApiToken>> getToken(@PathVariable String uuid,
                                                     @RequestParam(value = "name", required = false) String notes) {
        notes = StringUtils.hasText(notes) ? notes : "Global";
        ApiToken apiToken = apiTokenQuery.query(uuid, notes);

        return ok(apiToken);
    }

    @PutMapping("/{switch}")
    public ResponseEntity<Result<Void>> switchToken(@PathVariable String uuid,
                                                    @PathVariable("switch") String onOff,
                                                    @RequestParam(value = "name", required = false) String notes) {
        notes = StringUtils.hasText(notes) ? notes : "Global";
        gendbApiTokenService.switchToken(uuid, notes, onOff);
        return none();
    }

    @PutMapping
    public ResponseEntity<Result<Void>> resetToken(@PathVariable String uuid,
                                                   @RequestParam(value = "name", required = false) String notes,
                                                   @RequestParam(value = "async", required = false) boolean async) {
        notes = StringUtils.hasText(notes) ? notes : "Global";
        gendbApiTokenService.reset(uuid, notes, async);

        return accepted();
    }

    @DeleteMapping
    public ResponseEntity<Result<Void>> deleteToken(@PathVariable String uuid,
                                                    @RequestParam(value = "name", required = false) String notes) {
        notes = StringUtils.hasText(notes) ? notes : "Global";
        gendbApiTokenService.remove(uuid, notes);

        return accepted();
    }
}
